<?php


namespace app\common\cachemodel;


use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\cachemodel\zl7\Zl7AiAnswerNumData;
use app\common\cachemodel\zl7\Zl7QuestionAiAnswerRecord;
use app\common\lib\Util;
use app\common\model\BaseCache;
use think\Env;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlTarotRecords extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_tarot_records';

    protected $cacheModel = 'divination.tarot_record';

    /**
     * 牌阵 阵型信息  1=>【3牌阵】 2=>【四牌阵(上二下二)】 3=>【四牌阵（上一下三）】
     * @var array
     */
    public $tarotTypeFlag = [
        1 => 1, // 1号牌阵（免费）
        2 => 1, // 2号牌阵（感情发展）
        3 => 2, // 3号牌阵（桃花运势）
        4 => 3, // 4号牌阵（分手复合）
    ];

    /**
     * 塔罗占卜信息写入
     * @param int $uid
     * @param array $data
     * @return false|int
     */
    public function saveData(int $uid, array $data)
    {
        try
        {
            $tarotId = $this->insertGetId($data);

            $this->listDataAdd($uid, [$tarotId => $tarotId]);
        }
        catch (\Exception $e)
        {
            return false;
        }

        return (int)$tarotId;
    }

    /**
     * 塔罗
     * @param $tarotId
     * @param array $data 更新数据
     * @return bool
     */
    public function updateData($tarotId, $data)
    {
        try
        {
            $this->where('id', $tarotId)->update($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $tarotId)->setCache($data); // 更新详情缓存
        }
        catch (\Exception $e)
        {
            Log::write('塔罗占卜删除错误：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            return false;
        }
        return true;
    }

    /**
     * 删除塔罗占卜记录
     * @param int $uid 用户ID
     * @param int $tarotId 塔罗占卜记录ID
     * @return bool
     */
    public function delData(int $uid, int $tarotId): bool
    {
        try
        {
            $this->where('id', $tarotId)->update(['is_del' => 1]);
            $this->listDataDel($uid, [$tarotId]); // 删除列表项
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $tarotId)->rmCache(); // 删除详情缓存
        }
        catch (\Exception $e)
        {
            Log::write('塔罗占卜删除错误：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」");
            return false;
        }
        return true;
    }

    /**
     * 列表数据重组
     * @param array $pageData
     * @param int $type 1=>旧版本塔罗 2=>新版本塔罗[2.12.0]
     * @return array
     * @throws \Exception
     */
    public function pageDataReset(array $pageData, int $type)
    {
        $pageData = $this->dataInit($pageData);
        $resData = [];
        $tarotConfig = config('tarot');
        $oss = Env::get('host.photo');
        foreach ($pageData as $itemData)
        {
            $tarotCards = [];
            if ($itemData['type'] === 3)
            {
                foreach ($itemData['content'] as $tarotItem)
                {
                    $tarotCards[] = [
                        'img' => "/test/tarot/cards/{$tarotItem['card_id']}-{$tarotItem['direction']}.png",
                        'tips' => $tarotConfig['tarot_type'][$itemData['tarot_type']][$tarotItem['location']]['tip'],
                        'name' => $tarotConfig['card_list'][$tarotItem['card_id']]['name'] . '.' . ((int)$tarotItem['direction'] === 1 ? '正位' : '逆位'),
                    ];
                }
                $tag = $itemData['status'] === 1 ? $oss . '/test/ai/divination_tarot_ai.png' : '';
            } else
            {
                foreach ($itemData['content'] as $tarotItem)
                {
                    $tarotCards[] = [
                        'img' => "/test/tarot/cards/{$tarotItem['card_id']}-{$tarotItem['direction']}.png",
                        'tips' => $tarotConfig['tarot_type'][$tarotItem['type']][$tarotItem['location']]['tip'],
                        'name' => $tarotConfig['card_list'][$tarotItem['card_id']]['name'] . '.' . ((int)$tarotItem['direction'] === 1 ? '正位' : '逆位'),
                    ];
                }
                $aiContent = (new Zl7QuestionAiAnswerRecord())->getUserAiInfo(2, $itemData['uid'], $itemData['id'])['content'];
                $tag = $aiContent !== null ? $oss . '/test/ai/divination_tarot_ai.png' : '';
            }
            $item = [
                'tarot_id' => (int)$itemData['id'],
                'question' => $itemData['question'],
                'tarot_cards' => $tarotCards,
                'time' => date('Y-m-d H:i', $itemData['create_time']),
                'del_msg' => ($itemData['gid'] && $itemData['status']) ? '此记录为付费记录，确定要删除此记录吗？' : '确定要删除此记录吗？', // 支付过的不能删除
                'flag' => $this->tarotTypeFlag[$itemData['tarot_type']] ?? $itemData['tarot_type'],
                'tag' => $tag,
            ];
            if ($type === 2)
            {   // 新版本塔罗
                $item['type'] = $itemData['type'] === 3 ? 2 : 1;
                $item['name'] = $itemData['type'] === 3 ? $tarotConfig['tarot_type_name'][$itemData['tarot_type']] : '';
            }
            $resData[] = $item;
        }

        return $resData;
    }

    /**
     * 获取塔罗占卜详情结果信息
     * @param array $data
     * @return array
     * @throws \Exception
     */
    public function getDetails(array $data): array
    {
        $tarotData = $data['content'];
        $status = (int)$data['status'];
        $unlockBtn = '';
        $cardTexts = [];
        if ($status)
        {
            // 获取解锁后的词条信息
            $cardIds = [];
            foreach ($tarotData as $tarotItem)
            {
                $cardIds[] = $tarotItem['text_id'];
            }
            // 获取塔罗词条信息
            if ($cardIds)
            {
                $cardTexts = (new ZlTarotText())->batchGetInfoByIds($cardIds, ['text']);
            }
        } else
        {
            $googInfo = (new Goods())->getInfoById($data['gid'], ['now_prize']);
            $unlockBtn = $googInfo['now_prize'] . '元解锁查看详细解读';
        }

        $tarotConfig = config('tarot');
        $tarotCards = [];
        $keywordPrefix = Util::CheckAppVersion('2.5.5') !== '小' ? '' : '关键词：';
        foreach ($tarotData as $tarotItem)
        {
            $locationKey = (int)$data['status'] === 1 ? 'tip_detail2' : 'tip_detail1';
            $tarotCards[] = [
                'img' => "/test/tarot/cards/{$tarotItem['card_id']}-{$tarotItem['direction']}.png",
                'tips' => $tarotConfig['tarot_type'][$tarotItem['type']][$tarotItem['location']]['tip'],
                'name' => $tarotConfig['card_list'][$tarotItem['card_id']]['name'] . '.' . ((int)$tarotItem['direction'] === 1 ? '正位' : '逆位'),  // 牌名及正逆位
                'location' => $tarotConfig['tarot_type'][$tarotItem['type']][$tarotItem['location']][$locationKey], // 牌位信息
                'keyword' => $status ? ($keywordPrefix . ($tarotConfig['card_list'][$tarotItem['card_id']]['keyword' . $tarotItem['direction']] ?? '关键词缺失')) : '',
                'content' => $status ? ($cardTexts[$tarotItem['text_id']]['text'] ?? '词条缺失') : '',
                'desc' => $tarotConfig['card_list'][$tarotItem['card_id']]['desc'] ?? '词条缺失',
            ];
        }

        $customer_service = $this->getCustomService();
        $aiAnswer = (new ZlTarotRecords())->getAiAnswer(2, $data);
        return [
            'question' => $data['question'],
            'tarot_cards' => $tarotCards,
            'status' => $status,
            'flag' => $this->tarotTypeFlag[$data['tarot_type']],
            'gid' => (int)$data['gid'],
            'unlock_btn' => $unlockBtn,
            'create_time' => '塔罗时间：' . date('Y.m.d H:i'),
            'customer_service' => $customer_service,
            'ai_answer' => $aiAnswer,
        ];
    }

    /**
     * 获取咨询师入口信息
     * @return array
     */
    public function getCustomService()
    {
        $appType = request()->header('app-type');
        if ($appType == 'ios')
        {
            $customer_service = [
                'title' => Util::CheckAppVersion('2.8.0') === '小' ? '人工咨询' : '咨询师解答',
                'status' => 1,
                'target' => 'link',
//                'link' => 'https://qr34.cn/EGF7t4'
                'link' => 'https://wechat.goddessxzns.com/web/dice_ask/tarot.html',// 安卓跳两下，写死
            ];
        } else
        {
            //安卓问答版本咨询入口关闭
            if (Util::CheckAppVersion('2.8.0') === '小')
            {
                $customer_service = [
                    'title' => '人工咨询',
                    'status' => 1,
                    'target' => 'link',
                    'link' => 'https://wechat.goddessxzns.com/web/dice_ask/tarot.html',// 安卓跳两下，写死
                ];
            } elseif (Util::CheckAppVersion('2.8.4') !== '小')
            {
                $customer_service = [
                    'title' => '咨询师解答',
                    'status' => 1,
                    'target' => 'link',
                    'link' => 'https://wechat.goddessxzns.com/web/dice_ask/tarot.html',// 安卓跳两下，死
                ];
                //android 直播间里的骰子提问有bug，在2.9.4版本之前的，需要返回null，否则会有崩溃
                if (Util::CheckAppVersion('2.9.4') === '小')
                {
                    $customer_service = null;
                }
            } else
            {
                $customer_service = [
                    'title' => '咨询师解答',
                    'status' => 0,
                    'target' => 'link',
                    'link' => 'https://wechat.goddessxzns.com/web/dice_ask/tarot.html',// 安卓跳两下，写死
                ];
            }
        }
        if (Util::AppIsPassShowV1())
        {
            $customer_service['status'] = 0;
        }
        if (Util::IsOppo() && Util::checkAppVersion('2.14.1') !== '小' && Util::AppIsPassShowV1())
        {
            $customer_service = null;
        }
        return $customer_service;
    }

    /**
     * 获取AI解答状态
     * @param $type 1=>骰子  2=>塔罗
     * @param $detail
     * @return array
     * @throws \Exception
     */
    public function getAiAnswer($type, $detail)
    {
        $aiContent = (new Zl7QuestionAiAnswerRecord())->getUserAiInfo($type, $detail['uid'], $detail['id'])['content'];
        if (Util::checkAppVersion('2.15.0') !== '小')
        {
            $numData = (new HzChatRecordDetails())->getChatQueryEndNumRes($detail['uid']);
            $resNum = $numData['res_num'];
        } else
        {
            $num = (new Zl7AiAnswerNumData())->getUserAiNum($detail['uid']);
            $resNum = (int)$num['ai_num'] + $num['admin_num'];
        }
        return [
            'title' => $aiContent === null ? 'AI准准解答' : 'AI准准已解答',
            'status' => $aiContent === null ? 1 : 2,//0=>不显示 1=>未解答 2=>已解答
            'num' => $resNum,
        ];
    }

    /**
     * 批量获取塔罗记录数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->where(['id' => ['in', $ids]]);
            } else
            {
                $this->where(['uid' => $type[0]]);
            }

            $data = $this->where('is_del', 0)->order("id {$sortType}")->column('uid,question,type,gid,status,tarot_type,content,order_num,create_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取一个塔罗牌阵占卜次数
     * @param int $tarotType 牌阵
     * @return int|mixed
     * @throws \Exception
     */
    public function getDivinationNum(int $tarotType): int
    {
        $divinationNum = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->getDataAndSet(function ()
        {
            try
            {
                return $this->group('tarot_type')->column('count(tarot_type) as num', 'tarot_type');
            }
            catch (\Exception $e)
            {
                return [];
            }
        }, [$tarotType], 'divination_num');

        return is_array($divinationNum) ? $divinationNum[$tarotType] ?? 0 : $divinationNum ?: 0;
    }

    /**
     * 塔罗占卜次数增加
     * @param int $tarotType
     * @param int $inc
     * @throws \Exception
     */
    public function divinationNumAdd(int $tarotType, int $inc = 1): void
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)->hashDataInc($tarotType, $inc, function () use ($tarotType)
        {
            try
            {
                return $this->where('tarot_type', $tarotType)->count();
            }
            catch (\Exception $e)
            {
                return 0;
            }
        }, 'divination_num');
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'type', 'gid', 'status', 'tarot_type', 'create_time', 'update_time']);

            if (isset($itemData['content']))
            {
                $data[$index]['content'] = $itemData['content'] ? json_decode($itemData['content'], true) : [];
            }
        }

        return $data;
    }
}
